package com.example.administrator.base.activity;

import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.erebus.blelocklibrary.config.Config;
import com.erebus.blelocklibrary.config.LockType;
import com.erebus.blelocklibrary.impl.AndroidBle;
import com.erebus.blelocklibrary.inter.IBLE;
import com.erebus.blelocklibrary.inter.OnConnectionListener;
import com.erebus.blelocklibrary.inter.OnDeviceSearchListener;
import com.erebus.blelocklibrary.utils.GlobalParameterUtils;
import com.example.administrator.base.baseActivity.BaseActivity;
import com.example.administrator.base.bean.OpenLock;
import com.example.administrator.base.bean.ReLogout;
import com.example.administrator.base.R;
import com.example.administrator.base.util.BLEStringUtils;
import com.example.administrator.base.util.GsonTools;
import com.example.administrator.base.util.SharedPreferencesUtils;
import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import java.io.IOException;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ScanActivity extends BaseActivity implements CodeUtils.AnalyzeCallback, SensorEventListener {

    @InjectView(R.id.Toolbar)
    android.support.v7.widget.Toolbar Toolbar;
    @InjectView(R.id.et_carnumber)
    EditText etCarnumber;
    @InjectView(R.id.light_tip)
    TextView lightTip;
    CaptureFragment captureFragment;
    private boolean isLightOpen = false;
    boolean canOpenLight = false;
    boolean ischange=false;
    String type = "";
    private IBLE ible;
    BroadcastReceiver broadcastReceiver;
    SweetAlertDialog sweetAlertDialog;
    private SensorManager sm;
    private int bleStatus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);
        ButterKnife.inject(this);
        captureFragment = new CaptureFragment();
        CodeUtils.setFragmentArgs(captureFragment, R.layout.view_camera);
        captureFragment.setAnalyzeCallback(this);
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, captureFragment).commit();
        bleStatus = 0;
        sm = (SensorManager) this.getSystemService(SENSOR_SERVICE);
        sweetAlertDialog = new SweetAlertDialog(this, 5);
        sweetAlertDialog.setCanceledOnTouchOutside(false);
        sweetAlertDialog.setTitleText("加载中");
        Intent intent = getIntent();
        type = intent.getStringExtra("type");
        Log.i("5156416152", "" + type);
        Toolbar.setTitle("赳猎人");
        Toolbar.setSubtitle("扫二维码");
        setSupportActionBar(Toolbar);
        Toolbar.setNavigationIcon(R.drawable.backbar);
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        if (type.equals("openlockb")) {
            ible = new AndroidBle(this);
            if (!ible.isEnable()) {
                showToast("请打开蓝牙");
                ible.enableBluetooth();
            }
        }
        if (type.equals("lockmessage")) {
            ible = new AndroidBle(this);
            if (!ible.isEnable()) {
                showToast("请打开蓝牙");
                ible.enableBluetooth();
            }
        }

        etCarnumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                final String result = s.toString();
                if (result.length() == 9) {
                    vibrate();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (type.equals("lockCar")) {
                                sweetAlertDialog.show();
                                bandcar(result);
                            }

                            if (type.equals("openlockb")) {
                                sweetAlertDialog.show();
                                if (ible.isEnable()) {
                                    getBluetooth(result, "1");
                                } else {
                                    sweetAlertDialog.dismiss();
                                    showToast("未打开蓝牙，无法进行蓝牙相关操作");
                                }
                            }

                            if (type.equals("openlock")) {
                                sweetAlertDialog.show();
                                getBluetooth2(result, "0");
                            }

                            if (type.equals("lockmessage")) {
                                sweetAlertDialog.show();
                                if (ible.isEnable()) {
                                    Log.i("0212121", "1");
                                    getLockMessage(result, "1");
                                } else {
                                    sweetAlertDialog.dismiss();
                                    showToast("未打开蓝牙，无法进行蓝牙相关操作");
                                }
                            }

                            if (type.equals("bandcar")) {
                                sweetAlertDialog.show();
                                dengjicar(result);
                            }

                            if (type.equals("bandlock")) {
                                sweetAlertDialog.show();
                                dengjilock(result);
                            }

                            if (type.equals("unbandcar")) {
                                sweetAlertDialog.show();
                                undengjicar(result);
                            }

                            if (type.equals("brokencar")) {
                                Intent intent = new Intent(ScanActivity.this, BrokenCarDetail.class);
                                intent.putExtra("car", result);
                                intent.putExtra("type", "brokencar");
                                startActivity(intent);
                                finish();
                            }

                            if (type.equals("brokenback")) {
                                Intent intent = new Intent(ScanActivity.this, BrokenCarDetail.class);
                                intent.putExtra("car", result);
                                intent.putExtra("type", "brokenback");
                                startActivity(intent);
                                finish();
                            }

                            if (type.equals("serchcar")) {
                                Intent intent = new Intent(ScanActivity.this, SerchCar.class);
                                intent.putExtra("car", result);
                                startActivity(intent);
                                finish();
                            }

                            if (type.equals("lockmessageG")) {
                                Intent intent = new Intent(ScanActivity.this, LockMessage.class);
                                intent.putExtra("car", result);
                                startActivity(intent);
                                finish();
                            }
                            if (type.equals("fixcar")) {
                                Intent intent = new Intent(ScanActivity.this, BrokenCarDetail.class);
                                intent.putExtra("car", result);
                                intent.putExtra("type", "fixcar");
                                startActivity(intent);
                                finish();
                            }
                            if (type.equals("serchpeople")) {
                                Intent intent = new Intent(ScanActivity.this, ResentUser.class);
                                intent.putExtra("car", result);
                                startActivity(intent);
                                finish();
                            }

                        }
                    }, 1000);

                }
            }
        });
    }


    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onPause() {
        canOpenLight = false;
        lightTip.setText("灯光 - 关闭");
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        canOpenLight = true;
        Sensor light = sm.getDefaultSensor(Sensor.TYPE_LIGHT);
        if (light != null) {
            sm.registerListener(this, light, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    @Override
    protected void onStart() {

        super.onStart();

    }

    @Override
    protected void onDestroy() {
        if (type.equals("openlockb")) {
            ible.disconnect();

        }
        if (type.equals("lockmessage")) {
            ible.disconnect();

        }
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
            broadcastReceiver = null;
        }
        super.onDestroy();
    }

    @Override
    protected void onResponseSuccess(Response response, String action) {

    }

    @Override
    protected void onResponseFailure(Throwable e, String action) {

    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    private void setLight() {
        if (!canOpenLight) return;
        isLightOpen = !isLightOpen;
        CodeUtils.isLightEnable(isLightOpen);
        lightTip.setText("灯光 - " + (isLightOpen ? "打开" : "关闭"));
    }

    @OnClick(R.id.fab_light)
    public void onClick() {
        ischange=true;
        setLight();
    }


    /*绑定五菱宏光*/
    public void bandcar(String carId) {
        Log.i("3378", String.valueOf(SharedPreferencesUtils.getParam(ScanActivity.this, "adminId", "")));
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "BINDINGCAR")
                .add("carId", carId)
                .add("adminId", String.valueOf(SharedPreferencesUtils.getParam(ScanActivity.this, "adminId", "")))
                .build();

        final Request request = new Request.Builder()
                .url("http://operate.99bicycle.com/OperateBicyclePro/administrator?")
                .post(formBody)
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        final ReLogout mse = GsonTools.changeGsonToBean(string, ReLogout.class);
                        if (mse != null) {
                            if (mse.getCode() == 1) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        sweetAlertDialog.dismiss();
                                        Toast.makeText(ScanActivity.this, "绑定车辆成功", Toast.LENGTH_LONG).show();
                                        finish();
                                    }
                                });
                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        sweetAlertDialog.dismiss();
                                        Toast.makeText(ScanActivity.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();
                                        captureFragment.restartScan();
                                    }
                                });
                            }

                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    sweetAlertDialog.dismiss();
                                    Toast.makeText(ScanActivity.this, "数据异常请重试", Toast.LENGTH_LONG).show();

                                }
                            });
                        }
                    } else {
                        throw new Exception("Unexpected code " + response);
                    }
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sweetAlertDialog.dismiss();
                        }
                    });
                    e.printStackTrace();
                }
            }
        }).start();


    }

    /*蓝牙开锁*/
    public void getBluetooth(final String carId, final String type) {
        Log.i("21451", "in");
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "ADMINOPENLOCK")
                .add("adminId", String.valueOf(SharedPreferencesUtils.getParam(ScanActivity.this, "adminId", "")))
                .add("bicycleNo", carId)
                .add("useBlueTooth", type)
                .build();

        final Request request = new Request.Builder()
                .url("http://operate.99bicycle.com/OperateBicyclePro/administrator?")
                .post(formBody)
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.i("21451", string);
                        final OpenLock mse = GsonTools.changeGsonToBean(string, OpenLock.class);
                        if (mse == null) {
                            return;
                        }
                        if (mse.getCode() == 1) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    broadcastReceiver = new BroadcastReceiver() {
                                        @Override
                                        public void onReceive(Context context, Intent intent) {
                                            String action = intent.getAction();
                                            String data = intent.getStringExtra("data");
                                            switch (action) {
                                                case Config.TOKEN_ACTION:
                                                    Log.d(TAG, "get token");
                                                    new Handler().postDelayed(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            ible.openLock();
                                                        }
                                                    }, 1000);
                                                    break;
                                                case Config.OPEN_ACTION:
                                                    if (TextUtils.isEmpty(data)) {
                                                        Log.d(TAG, "开锁失败");
                                                        Toast.makeText(ScanActivity.this, "开锁失败", Toast.LENGTH_LONG).show();
                                                        Changetype(carId, "0");

                                                    } else {
                                                        Log.d(TAG, "开锁成功");
                                                        Toast.makeText(ScanActivity.this, "开锁成功", Toast.LENGTH_LONG).show();
                                                        Changetype(carId, "1");
                                                    }

                                                    break;
                                            }
                                        }
                                    };

                                    registerReceiver(broadcastReceiver, Config.initFilter());
                                    GlobalParameterUtils.getInstance().setLockType(LockType.MTS);
                                    Config.key = getKey(mse.getKey());
                                    Config.password = getPassword(mse.getPass());
                                    final String mac = BLEStringUtils.encodeMAC(mse.getMac());
                                    Log.e("3378", "aaa");
                                    ible.startScan(new OnDeviceSearchListener() {
                                        @Override
                                        public void onScanDevice(final BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
                                            if (bluetoothDevice == null || TextUtils.isEmpty(bluetoothDevice.getAddress()))
                                                return;
                                            String bluetoothMac = bluetoothDevice.getAddress();
                                            if (mac.equalsIgnoreCase(bluetoothMac)) {
                                                Log.d("3378451844154", "finded");
                                                ible.stopScan();
                                                bleStatus = 0;
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        ible.connectDevice(bluetoothDevice, new OnConnectionListener() {
                                                            @Override
                                                            public void onConnect() {
                                                                Log.d("3378451844154", "onConnect");
                                                            }

                                                            @Override
                                                            public void onDisconnect(int state) {
                                                                Log.d("3378451844154", "连接失败");
                                                                if (!isFinishing()) {
                                                                    Log.d("3378451844154", "连接失败1");
                                                                    Log.i("3378451844154", "" + isFinishing());
                                                                    Toast.makeText(ScanActivity.this, "连接失败", Toast.LENGTH_LONG).show();
                                                                    Changetype(carId, "0");
                                                                }
                                                            }

                                                            @Override
                                                            public void onServicesDiscovered(String name, String address) {
                                                                getToken();
                                                            }
                                                        });
                                                    }
                                                });
                                            }

                                        }
                                    });
                                    bleStatus = 1;
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (!isFinishing() && ible.isEnable() && bleStatus == 1) {
                                                ible.stopScan();
                                                bleStatus = 0;
                                                Toast.makeText(ScanActivity.this, "连接超时", Toast.LENGTH_LONG).show();
                                                Changetype(carId, "0");
                                            }
                                        }
                                    }, 15 * 1000);
                                }
                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(ScanActivity.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();
                                    /*scannerView.onResume();*/
                                }
                            });
                        }

                    } else {
                        throw new Exception("Unexpected code " + response);
                    }
                } catch (Exception e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sweetAlertDialog.dismiss();
                            showToast("请检查您的网络是否开启");
                            captureFragment.restartScan();
                        }
                    });
                    e.printStackTrace();
                }
            }
        }).start();

    }


    /*GPRS开锁*/
    public void getBluetooth2(String carId, final String type) {
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "ADMINOPENLOCK")
                .add("adminId", String.valueOf(SharedPreferencesUtils.getParam(ScanActivity.this, "adminId", "")))
                .add("bicycleNo", carId)
                .add("useBlueTooth", type)
                .build();

        final Request request = new Request.Builder()
                .url("http://operate.99bicycle.com/OperateBicyclePro/administrator?")
                .post(formBody)
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {

                        String string = response.body().string();
                        Log.i("21451", "wtf:-----" + string);
                        final OpenLock mse = GsonTools.changeGsonToBean(string, OpenLock.class);
                        if (mse == null) {
                            return;
                        }
                        if (mse.getCode() == 1) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    Log.i("35555", "xx");
                                    Toast.makeText(ScanActivity.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();
                                    sweetAlertDialog.dismiss();
                                    finish();
                                }
                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(ScanActivity.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();
                                    sweetAlertDialog.dismiss();
                                   /* scannerView.onResume();*/
                                }
                            });
                        }

                    } else {
                        throw new IOException("Unexpected code " + response);
                    }
                } catch (IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sweetAlertDialog.dismiss();
                            showToast("请检查您的网络是否开启");
                            captureFragment.restartScan();
                        }
                    });
                    e.printStackTrace();
                    Log.i("21451", "11");
                }
            }
        }).start();


    }

    /*置位接口*/
    public void Changetype(String num, String type) {

        Log.i("3378", String.valueOf(SharedPreferencesUtils.getParam(ScanActivity.this, "adminId", "")));
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "ADMINOPENLOCKREPLY")
                .add("adminId", String.valueOf(SharedPreferencesUtils.getParam(ScanActivity.this, "adminId", "")))
                .add("bicycleNo", num)
                .add("isSuccess", type)
                .build();

        final Request request = new Request.Builder()
                .url("http://operate.99bicycle.com/OperateBicyclePro/administrator?")
                .post(formBody)
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.i("3378451844154", string);
                        ReLogout mse = GsonTools.changeGsonToBean(string, ReLogout.class);
                        if (mse != null) {
                            if (mse.getCode() == 1) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        sweetAlertDialog.dismiss();
                                        finish();
                                    }
                                });
                            }
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    sweetAlertDialog.dismiss();
                                    showToast("数据异常 请重试");
                                }
                            });
                        }
                    } else {
                        throw new IOException("Unexpected code " + response);
                    }
                } catch (IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sweetAlertDialog.dismiss();
                        }
                    });
                    e.printStackTrace();
                }
            }
        }).start();


    }

    /*获取锁蓝牙地址*/
    public void getLockMessage(final String carId, final String type) {
        Log.i("3378", String.valueOf(SharedPreferencesUtils.getParam(ScanActivity.this, "adminId", "")));
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "ADMINOPENLOCK")
                .add("adminId", String.valueOf(SharedPreferencesUtils.getParam(ScanActivity.this, "adminId", "")))
                .add("bicycleNo", carId)
                .add("useBlueTooth", type)
                .build();

        final Request request = new Request.Builder()
                .url("http://operate.99bicycle.com/OperateBicyclePro/administrator?")
                .post(formBody)
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        final String string = response.body().string();
                        Log.i("21451", string);
                        final OpenLock mse = GsonTools.changeGsonToBean(string, OpenLock.class);
                        if (mse == null) {
                            return;
                        }
                        if (mse.getCode() == 1) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Log.i("35555", "yy");
                                    Intent intent = new Intent(ScanActivity.this, LockManageActivity.class);
                                    intent.putExtra("key", mse.getKey());
                                    intent.putExtra("password", mse.getPass());
                                    intent.putExtra("mac", mse.getMac());
                                    intent.putExtra("re", string);
                                    startActivity(intent);
                                    finish();
                                }

                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(ScanActivity.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();
                                    sweetAlertDialog.dismiss();
                                   /* scannerView.onResume();*/

                                }
                            });
                        }

                    } else {
                        throw new IOException("Unexpected code " + response);
                    }
                } catch (IOException e) {
                    sweetAlertDialog.dismiss();
                    e.printStackTrace();
                }
            }
        }).start();

    }

    /*车辆绑定城市*/
    public void dengjicar(String carId) {
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "REGISTERCITYNO")
                .add("adminId", String.valueOf(SharedPreferencesUtils.getParam(ScanActivity.this, "adminId", "")))
                .add("bicycleNo", carId)
                .build();
        final Request request = new Request.Builder()
                .url("http://operate.99bicycle.com/OperateBicyclePro/administrator?")
                .post(formBody)
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        final ReLogout mse = GsonTools.changeGsonToBean(string, ReLogout.class);
                        Log.i("121555121", "" + string);
                        if (mse != null) {
                            if (mse.getCode() == 1) {
                                //电子围栏
                                if (mse.getResult() == 1) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(ScanActivity.this, "" + mse.getMesg(), Toast.LENGTH_LONG).show();
                                        }
                                    });

                                } else if (mse.getResult() == 528) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Toast.makeText(ScanActivity.this, "" + mse.getMesg(), Toast.LENGTH_LONG).show();
                                        }
                                    });
                                }
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(ScanActivity.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();
                                        sweetAlertDialog.dismiss();
                                        captureFragment.restartScan();
                                    }
                                });
                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(ScanActivity.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();
                                        sweetAlertDialog.dismiss();
                                        captureFragment.restartScan();
                                    }
                                });
                            }
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    sweetAlertDialog.dismiss();
                                    Toast.makeText(ScanActivity.this, "数据异常请重试", Toast.LENGTH_LONG).show();
                                }
                            });
                        }

                    } else {
                        throw new IOException("Unexpected code " + response);
                    }
                } catch (IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sweetAlertDialog.dismiss();
                        }
                    });
                    e.printStackTrace();
                }
            }
        }).start();


    }


    /*车锁登记*/
    public void dengjilock(String carId) {
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "FAULTLOCKCHANGEDREGISTERCITYNO")
                .add("adminId", String.valueOf(SharedPreferencesUtils.getParam(ScanActivity.this, "adminId", "")))
                .add("bicycleNo", carId)
                .build();
        final Request request = new Request.Builder()
                .url("http://operate.99bicycle.com/OperateBicyclePro/administrator?")
                .post(formBody)
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        final ReLogout mse = GsonTools.changeGsonToBean(string, ReLogout.class);
                        Log.i("121555121", "" + string);
                        if (mse != null) {
                            if (mse.getCode() == 1) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(ScanActivity.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();
                                        sweetAlertDialog.dismiss();
                                        captureFragment.restartScan();
                                    }
                                });
                            } else {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(ScanActivity.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();
                                        sweetAlertDialog.dismiss();
                                        captureFragment.restartScan();
                                    }
                                });
                            }
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    sweetAlertDialog.dismiss();
                                    captureFragment.restartScan();
                                    Toast.makeText(ScanActivity.this, "数据异常请重试", Toast.LENGTH_LONG).show();
                                }
                            });
                        }

                    } else {
                        throw new IOException("Unexpected code " + response);
                    }
                } catch (IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sweetAlertDialog.dismiss();
                            captureFragment.restartScan();
                        }
                    });
                    e.printStackTrace();
                }
            }
        }).start();


    }

    /*车辆解除绑定*/
    public void undengjicar(String carId) {
        String location = String.valueOf(SharedPreferencesUtils.getParam(ScanActivity.this, "changelocklocation", ""));
        final OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("action", "CANCELLATIONCITYNO")
                .add("adminId", String.valueOf(SharedPreferencesUtils.getParam(ScanActivity.this, "adminId", "")))
                .add("bicycleNo", carId)
                .add("address", location)
                .build();
        final Request request = new Request.Builder()
                .url("http://operate.99bicycle.com/OperateBicyclePro/administrator?")
                .post(formBody)
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        final ReLogout mse = GsonTools.changeGsonToBean(string, ReLogout.class);
                        Log.i("121555121", "" + string);
                        if (mse != null) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    sweetAlertDialog.dismiss();
                                    Toast.makeText(ScanActivity.this, "" + mse.getMessage(), Toast.LENGTH_LONG).show();
                                    captureFragment.restartScan();
                                }
                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    sweetAlertDialog.dismiss();
                                    Toast.makeText(ScanActivity.this, "数据异常请重试", Toast.LENGTH_LONG).show();
                                    captureFragment.restartScan();
                                }
                            });
                        }

                    } else {
                        throw new IOException("Unexpected code " + response);
                    }
                } catch (IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sweetAlertDialog.dismiss();
                            captureFragment.restartScan();
                        }
                    });
                    e.printStackTrace();
                }
            }
        }).start();


    }

    private byte[] getPassword(String passWord) {
        byte[] buf = new byte[passWord.length() / 2];
        for (int i = 0; i < buf.length; i++) {
            buf[i] = (byte) Integer.parseInt(passWord.substring(i * 2, i * 2 + 2));
        }
        return buf;
    }

    private byte[] getKey(String key) {
        byte[] buf = new byte[key.length() / 2];
        for (int i = 0; i < key.length() / 2; i++) {
            buf[i] = (byte) Integer.parseInt(key.substring(i * 2, i * 2 + 2));
        }
        return buf;
    }

    private void getToken() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                ible.getToken();
                Log.i("3378451844154", "" + ible.getToken());
            }
        }, 1500);
    }


    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
            float value = event.values[0];
            Log.i("321215454",""+ischange);
            if (value <= 10.0 &&!ischange) {
                isLightOpen=true;
                CodeUtils.isLightEnable(isLightOpen);
                lightTip.setText("灯光 - 打开");
            }

            if (value >100.0 &&!ischange) {
                isLightOpen=false;
                CodeUtils.isLightEnable(isLightOpen);
                lightTip.setText("灯光 - 关闭");
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
        Log.i("Scanview",result);


        vibrate();
        if (type.equals("lockCar")) {
            if (result.length() == 9) {
                sweetAlertDialog.show();
                bandcar(result);
            } else {
                Log.d(TAG, "准备再扫描");
                showToast("请勿扫描其他二维码");
                captureFragment.restartScan();
            }
        }


        if (result != null && result.startsWith("http://www.99bicycle.com/download/?b=")) {
            String param = result.split("\\?")[1];
            String[] bicycleNumParam = param.split("=");
            if (bicycleNumParam.length > 1) {
                String bicycleNum = bicycleNumParam[1];
                if (bicycleNum.length() == 9) {
                    vibrate();

                    if (type.equals("openlockb")) {

                        sweetAlertDialog.show();
                        if (ible.isEnable()) {
                            getBluetooth(bicycleNum, "1");
                        } else {
                            sweetAlertDialog.dismiss();
                            showToast("未打开蓝牙，无法进行蓝牙相关操作");
                            captureFragment.restartScan();
                        }
                    }

                    if (type.equals("openlock")) {

                        sweetAlertDialog.show();
                        getBluetooth2(bicycleNum, "0");
                    }

                    if (type.equals("lockmessage")) {

                        sweetAlertDialog.show();
                        if (ible.isEnable()) {
                            getLockMessage(bicycleNum, "1");
                        } else {
                            Log.i("2111215451", "11");
                            sweetAlertDialog.dismiss();
                            showToast("未打开蓝牙，无法进行蓝牙相关操作");
                            captureFragment.restartScan();
                        }
                    }

                    if (type.equals("bandcar")) {

                        sweetAlertDialog.show();
                        dengjicar(bicycleNum);
                    }

                    if (type.equals("bandlock")) {
                        sweetAlertDialog.show();
                        dengjilock(bicycleNum);
                    }

                    if (type.equals("unbandcar")) {

                        sweetAlertDialog.show();
                        undengjicar(bicycleNum);
                    }

                    if (type.equals("brokencar")) {

                        Intent intent = new Intent(ScanActivity.this, BrokenCarDetail.class);
                        intent.putExtra("car", bicycleNum);
                        intent.putExtra("type", "brokencar");
                        startActivity(intent);
                        finish();
                    }

                    if (type.equals("brokenback")) {

                        Intent intent = new Intent(ScanActivity.this, BrokenCarDetail.class);
                        intent.putExtra("car", bicycleNum);
                        intent.putExtra("type", "brokenback");
                        startActivity(intent);
                        finish();
                    }

                    if (type.equals("serchcar")) {

                        Intent intent = new Intent(ScanActivity.this, SerchCar.class);
                        intent.putExtra("car", bicycleNum);
                        startActivity(intent);
                        finish();
                    }

                    if (type.equals("lockmessageG")) {

                        Intent intent = new Intent(ScanActivity.this, LockMessage.class);
                        intent.putExtra("car", bicycleNum);
                        startActivity(intent);
                        finish();
                    }
                    if (type.equals("fixcar")) {
                        Intent intent = new Intent(ScanActivity.this, BrokenCarDetail.class);
                        intent.putExtra("car", bicycleNum);
                        intent.putExtra("type", "fixcar");
                        startActivity(intent);
                        finish();
                    }
                    if (type.equals("serchpeople")) {
                        Intent intent = new Intent(ScanActivity.this, ResentUser.class);
                        intent.putExtra("car", bicycleNum);
                        startActivity(intent);
                        finish();
                    }


                } else {
                    captureFragment.restartScan();
                }
            } else {
                captureFragment.restartScan();
            }
        } else {
            showToast("请勿扫描其他二维码");
            captureFragment.restartScan();
        }
    }

    @Override
    public void onAnalyzeFailed() {
        showToast("扫描失败，请检查是否给予权限");
        captureFragment.restartScan();
    }
}
